package com.sptus.web.controller.system;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.ObjectCodec;
import com.sptus.common.constant.CommonConstant;
import com.sptus.common.core.domain.entity.SysMenu;
import com.sptus.common.core.domain.model.LoginUser;
import com.sptus.common.core.redis.RedisCache;
import com.sptus.system.utils.GmailSendVerificationCode;
import com.sptus.common.utils.uuid.IdUtils;
import com.sptus.framework.service.BaseCommonService;
import com.sptus.framework.web.service.SysPermissionService;
import com.sptus.framework.web.service.TokenService;
import com.sptus.system.service.*;
import com.sptus.web.config.DataLoaderConfig;
import com.sptus.web.vo.SignUpVO;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.sptus.common.annotation.Log;
import com.sptus.common.core.controller.BaseController;
import com.sptus.common.core.domain.AjaxResult;
import com.sptus.common.core.domain.entity.SysDept;
import com.sptus.common.core.domain.entity.SysRole;
import com.sptus.common.core.domain.entity.SysUser;
import com.sptus.common.core.page.TableDataInfo;
import com.sptus.common.enums.BusinessType;
import com.sptus.common.utils.SecurityUtils;
import com.sptus.common.utils.StringUtils;
import com.sptus.common.utils.poi.ExcelUtil;

/**
 * 用户信息
 * 
 * @author sptus
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController
{

    @Value(value = "${spt.emailUrl}")
    private String emailUrl;
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;



    @Autowired
    private RedisCache redisCache;

    @Autowired
    private TokenService tokenService;
    public  static ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
    @Autowired
    private ObjectCodec objectCodec;
    @Autowired
    private BaseCommonService baseCommonService;

    /**
     * 获取用户列表
     */
//    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody  SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user)
    {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        AjaxResult ajax = AjaxResult.success();

        if (StringUtils.isNotNull(userId))
        {
            userService.checkUserDataScope(userId);
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user)
    {
        deptService.checkDeptDataScope(user.getDeptId());
//        roleService.checkRoleDataScope(user.getRoleIds());
        if (!userService.checkUserNameUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        baseCommonService.addLog("添加用户，username： " +user.getUserName() , CommonConstant.LOG_TYPE_2, 2);
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }
//    @Log(title = "用户管理", businessType = BusinessType.INSERT)
//    @PostMapping("")
//    public AjaxResult add(@Validated @RequestBody SysUser user)
//    {
//        deptService.checkDeptDataScope(user.getDeptId());
////        roleService.checkRoleDataScope(user.getRoleIds());
//        if (!userService.checkUserNameUnique(user))
//        {
//            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
//        }
//        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
//        {
//            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
//        }
//        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
//        {
//            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
//        }
//        user.setCreateBy(getUsername());
//        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
//        return toAjax(userService.insertUser(user));
//    }



    @PostMapping("/SignUpUser")
    public AjaxResult SignUpUser( @RequestBody SysUser user)
    {
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isNotEmpty(user.getUserName()) && !userService.checkEmailUnique(user))
        {
            return error("Add a new user'" + user.getUserName() + "' Failed, the email account already exists");
        }
        String token = IdUtils.fastSimpleUUID();

        user.setCreateTime(new Date());
        user.setStatus("0");
        Object cacheObject = redisCache.getCacheObject("signUpUserEmail:" + user.getUserName());
        SysRole sysRole = new SysRole();

        String roleIds="";
        for (Long roleId : user.getRoleIds()) {
            roleIds+=","+roleId;
        }
        sysRole.setRoleIds(roleIds.substring(1));
        List<SysRole>  roles=roleService.getRoleByIds(sysRole);
        user.setRoles(roles);
        Set<String> menuPermission = permissionService.getMenuPermission(user);
        user.setPermissions(menuPermission);
        String jsonString = JSONObject.toJSONString(user);
        if(!ObjectUtils.isEmpty(cacheObject)){
            redisCache.deleteObject("signUpUserToken:"+cacheObject.toString());
        }
        redisCache.setCacheObject("signUpUserEmail:"+user.getUserName(),token);
        redisCache.setCacheObject("signUpUserToken:"+token,jsonString);
        String from = DataLoaderConfig.getGlobalData().get("spt.auth.code.email") ; // 发件人邮箱（你的Gmail）
        String host = DataLoaderConfig.getGlobalData().get("spt.auth.code.email.host") ; // SMTP服务器地址
        String port =  DataLoaderConfig.getGlobalData().get("spt.auth.code.email.post"); // Gmail SMTP端口
        String username =  DataLoaderConfig.getGlobalData().get("spt.auth.code.email.username");
        String password = DataLoaderConfig.getGlobalData().get("spt.auth.code.email.pass");
        String userName = user.getUserName();
        String verificationCode=emailUrl+token;
        String reviewers =DataLoaderConfig.getGlobalData().get("spt.auth.email");
        try {
            cachedThreadPool.submit(new Thread(new Runnable() {
                @Override
                public void run() {
                    GmailSendVerificationCode.sendEmailWithVerificationCode(reviewers,userName,"Link", verificationCode, from, host, port, username, password);
                }
            }));
        }catch (Exception e){
            //自定义异常
            e.printStackTrace();
            throw new RuntimeException("邮箱发送失败");
        }finally {

        }
        return toAjax(true);
    }
    @PostMapping("/getUserExist")
    public AjaxResult getUserExist( @RequestBody SysUser user)
    {
        if (StringUtils.isNotEmpty(user.getUserName()) && !userService.checkEmailUnique(user))
        {
            return error("Add a new user'" + user.getUserName() + "' Failed, the email account already exists");
        }
        return toAjax(true);
    }


    @GetMapping("/getUserToken")
    public AjaxResult getUserToken(String token)
    {
        Object cacheObject = redisCache.getCacheObject("signUpUserToken:"+token);
        SysUser sysUser=null;
        if (cacheObject != null) {
             sysUser = JSONObject.parseObject(cacheObject.toString(), SysUser.class);
            String userName = sysUser.getUserName();
            Object signUpUserEmail = redisCache.getCacheObject("signUpUserEmail:" + userName);
            if(signUpUserEmail !=null){
                String string = signUpUserEmail.toString();
                if (string.equals(token)) {
                    return success(sysUser);
                }
            }
        }
            return error("Broken links");

    }
    @GetMapping("/getMenuByToken")
    public AjaxResult getMenuByToken(String token)
    {
        Object cacheObject = redisCache.getCacheObject("signUpUserToken:"+token);
        SysUser sysUser=null;
        if (cacheObject != null) {
            sysUser = JSONObject.parseObject(cacheObject.toString(), SysUser.class);
            String userName = sysUser.getUserName();
            Object signUpUserEmail = redisCache.getCacheObject("signUpUserEmail:" + userName);
            if(signUpUserEmail !=null){
                String string = signUpUserEmail.toString();
                if (string.equals(token)) {
                    ArrayList<SysMenu> menus= menuService.selectMenuAll();
                    Set<String> permissions = sysUser.getPermissions();
                    for (SysMenu menu : menus) {
                        menu.setChecked(permissions.contains(menu.getPerms()));
                    }
                    return success(menus);
                }
            }
        }
        return error("Broken links");

    }
    @GetMapping("/getMenu")
    public AjaxResult getMenuByToken(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        ArrayList<SysMenu> menus= menuService.selectMenuAll();
        Set<String> menuPermission = permissionService.getMenuPermission(sysUser);

        for (SysMenu menu : menus) {
            menu.setChecked(menuPermission.contains(menu.getPerms()));
        }
        return success(menus);

    }
    @GetMapping("/getMenuByRole")
    public AjaxResult getMenuByRole(Long roleId)
    {
        Set<String> menuPermission = menuService.selectMenuPermsByRoleId(roleId);
        ArrayList<SysMenu> menus= menuService.selectMenuAll();
        for (SysMenu menu : menus) {
            menu.setChecked(menuPermission.contains(menu.getPerms()));
        }
        return success(menus);

    }


    @PostMapping("updateRole")
    public AjaxResult updateRole( @RequestBody SysRole role)
    {
        if (roleService.updateRole(role) > 0)
        {
            // 更新缓存用户权限
            LoginUser loginUser = getLoginUser();
            if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin())
            {
                loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
                loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
                tokenService.setLoginUser(loginUser);
            }
            return success();
        }
        return error("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
    }


    @PostMapping("/saveUser")
    public AjaxResult saveUser( @RequestBody SignUpVO user)
    {
        String from = DataLoaderConfig.getGlobalData().get("spt.auth.code.email") ; // 发件人邮箱（你的Gmail）
        String host = DataLoaderConfig.getGlobalData().get("spt.auth.code.email.host") ; // SMTP服务器地址
        String port =  DataLoaderConfig.getGlobalData().get("spt.auth.code.email.post"); // Gmail SMTP端口
        String username =  DataLoaderConfig.getGlobalData().get("spt.auth.code.email.username");
        String password = DataLoaderConfig.getGlobalData().get("spt.auth.code.email.pass");
        Object cacheObject = redisCache.getCacheObject("signUpUserToken:"+user.getToken());
        SysUser sysUser=null;
        if (cacheObject != null) {

            sysUser = JSONObject.parseObject(cacheObject.toString(), SysUser.class);
            String userName = sysUser.getUserName();
            Object signUpUserEmail = redisCache.getCacheObject("signUpUserEmail:" + userName);
            String Account = sysUser.getUserName();
//            redisCache.deleteObject("signUpUserEmail:"+sysUser.getUserName());
//            redisCache.deleteObject("signUpUserToken:"+signUpUserEmail);
            String to=sysUser.getUserName();
            if(sysUser.getStatus().equals("0")){
                String string = signUpUserEmail.toString();
                if (string.equals(user.getToken())) {
                    if(user.getIsApprove()){
                        sysUser.setMenuIds(user.getMenuIds());
                        sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
                        baseCommonService.addLog("添加用户，username： " +sysUser.getUserName() ,CommonConstant.LOG_TYPE_2, 2);
                        int i = userService.insertUser(sysUser);
                        sysUser.setStatus("1");
                        String jsonString = JSONObject.toJSONString(sysUser);
                        redisCache.setCacheObject("signUpUserToken:"+signUpUserEmail,jsonString);
                        if(i>0){
                            cachedThreadPool.submit(new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    String verificationCode="Registration is successful";
                                    if(!user.getIsApprove()){
                                        verificationCode="The request has been denied";
                                    }
                                    GmailSendVerificationCode.sendEmailWithVerificationCode(to,Account,"Result",verificationCode, from, host, port, username, password);
                                }
                            }));
                        }

                        return toAjax(i);
                    }else {
                        sysUser.setStatus("2");
                        String jsonString = JSONObject.toJSONString(sysUser);
                        redisCache.setCacheObject("signUpUserToken:"+signUpUserEmail,jsonString);
                        return toAjax(true);
                    }

                }
            }
        }
        return error("Broken links");

    }




    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:update')")
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
//        deptService.checkDeptDataScope(user.getDeptId());
//        roleService.checkRoleDataScope(user.getRoleIds());
        if (!userService.checkUserNameUnique(user))
        {
            return error("Modify user'" + user.getUserName() + "'Failed, the login account already exists");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("Modify user'" + user.getUserName() + "'Failed, The mobile number already exists");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("Modify user'" + user.getUserName() + "'Failed, An email account already exists");
        }
        user.setUpdateBy(getUsername());
        if(!ObjectUtils.isEmpty(user.getPassword())){
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        }
        return toAjax(userService.updateUser(user));
    }

//    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("edit")
    public AjaxResult editUser(@Validated @RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        boolean equals = user.getUserName().equals(getUsername());
        if (!equals) {
            return error("Modify user'" + user.getUserName() + "'Failed,Please modify this account");
        }
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user))
        {
            return error("Modify user'" + user.getUserName() + "'Failed, the login account already exists");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("Modify user'" + user.getUserName() + "'Failed, The mobile number already exists");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("Modify user'" + user.getUserName() + "'Failed, An email account already exists");
        }
        user.setUpdateBy(getUsername());
        if(!ObjectUtils.isEmpty(user.getPassword())){
            baseCommonService.addLog("Edit User  "+user.getUserName()+" password，操作人： " +getUsername() ,CommonConstant.LOG_TYPE_1, 2);
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        }
        baseCommonService.addLog("编辑用户，username： " +user.getUserName() ,CommonConstant.LOG_TYPE_2, 2);
        return toAjax(userService.updateByUser(user));
    }


    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        if (ArrayUtils.contains(userIds, getUserId()))
        {
            return error("The current user cannot delete");
        }
        baseCommonService.addLog("删除用户，id： " +userIds ,CommonConstant.LOG_TYPE_2, 3);
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds)
    {
        userService.checkUserDataScope(userId);
        roleService.checkRoleDataScope(roleIds);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept)
    {
        return success(deptService.selectDeptTreeList(dept));
    }
}
